package com.huobi;

import com.huobi.client.AccountClient;
import com.huobi.client.GenericClient;
import com.huobi.client.MarketClient;
import com.huobi.client.TradeClient;
import com.huobi.client.req.account.AccountBalanceRequest;
import com.huobi.client.req.account.AccountLedgerRequest;
import com.huobi.client.req.trade.CreateOrderRequest;
import com.huobi.client.req.wallet.CreateWithdrawRequest;
import com.huobi.client.req.wallet.DepositWithdrawRequest;
import com.huobi.constant.HuobiOptions;
import com.huobi.constant.enums.DepositWithdrawTypeEnum;
import com.huobi.model.account.*;
import com.huobi.model.generic.Symbol;
import com.huobi.model.market.MarketTicker;
import com.huobi.model.trade.Order;
import com.huobi.model.wallet.DepositWithdraw;
import com.huobi.service.huobi.HuobiWalletService;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.UUID;

public class HuobiInfoUtils {

    public static void main(String[] args) {

        String API_KEY = "3d16476a-ecc64c2d-315a7601-rfhfg2mkl3";
        String SECRET_KEY = "078a15fa-a6348193-b9f1ea86-7700f";
        String clientOrderId = UUID.randomUUID().toString().replace("-", "");
        //204629018476948
        final Order order = Order(API_KEY, SECRET_KEY, 204629018476948L);
        System.out.println(order);


    }


    public static Order getOrderByClientOrderId(String apikey, String secret, String clientOrderId) {
        TradeClient tradeService = TradeClient.create(HuobiOptions.builder()
                .apiKey(apikey)
                .secretKey(secret)
                .build());
        Order clientOrder = tradeService.getOrder(clientOrderId);
        System.out.println("查询客户端订单=" + clientOrder.toString());

        return clientOrder;
    }

    public static Long createBuyOrder(String apikey, String secret, String clientOrderId,
                                      String symbol, BigDecimal nowprice, BigDecimal price) {
        //新建买单服务
        TradeClient tradeService = TradeClient.create(HuobiOptions.builder()
                .apiKey(apikey)
                .secretKey(secret)
                .build());
        long spotAccountId = account_id(apikey, secret);

        //Symbol precision = getPrecision(symbol);

        //price = price.setScale(precision.getValuePrecision(), RoundingMode.HALF_UP);
        System.out.println("1.spotAccountId=:" + spotAccountId + " 购买了：" + symbol + " 订单金额：" + price
                +" 客户端订单id：" + clientOrderId);
        CreateOrderRequest buyMarketRequest = CreateOrderRequest
                .spotBuyMarket(spotAccountId,clientOrderId, symbol, price);
        Long buyLimitId = tradeService.createOrder(buyMarketRequest);

        System.out.println("2.spotAccountId=:" + spotAccountId + " 购买了：" + symbol + " 订单金额：" + price
                +" 客户端订单id：" + clientOrderId);

        return buyLimitId;
    }


    public static Symbol getPrecision(String symbol) {
        GenericClient genericService = GenericClient.create(HuobiOptions.builder().build());
        List<Symbol> symbolList = genericService.getSymbols();
        for (Symbol symbolitem : symbolList) {
            if (symbolitem.getSymbol().equals(symbol)) {
                return symbolitem;
            }
        }

        return null;
    }

    public static Long createSellOrder(String apikey, String secret, String clientOrderId, String symbol, BigDecimal amount) {
        //新建卖出账单服务
        TradeClient tradeService = TradeClient.create(HuobiOptions.builder()
                .apiKey(apikey)
                .secretKey(secret)
                .build());
        long spotAccountId = account_id(apikey, secret);

        Symbol precision = getPrecision(symbol);
        MarketTicker bizhongPrice = getBizhongPrice(symbol);

        BigDecimal askPrice = bizhongPrice.getClose().setScale(precision.getPricePrecision(), RoundingMode.HALF_UP);
        //.multiply(new BigDecimal(0.998))
        amount = amount.multiply(new BigDecimal(0.998)).setScale(precision.getAmountPrecision(), RoundingMode.HALF_UP);

        if (amount.compareTo(precision.getLimitOrderMinOrderAmt()) <= 0) {
            amount = precision.getLimitOrderMinOrderAmt();
            //return  null;
        }
        if (amount.compareTo(precision.getLimitOrderMaxOrderAmt()) > 0) {
            amount = precision.getLimitOrderMaxOrderAmt();
        }
        amount = amount.setScale(precision.getAmountPrecision(), RoundingMode.HALF_UP);

        System.out.println("火币工具  "+bizhongPrice.getSymbol()+"货币卖出 数量=" + amount + " MAX=" + precision.getLimitOrderMaxOrderAmt() + " MIN=" + precision.getLimitOrderMinOrderAmt());



        CreateOrderRequest sellMarketRequest = CreateOrderRequest
                .spotSellMarket(spotAccountId,clientOrderId, symbol, amount);


        Long sellLimitId = tradeService.createOrder(sellMarketRequest);

        System.out.println("spotAccountId=:" + spotAccountId + " 出手了：" + symbol + " 数量：" + amount
                + "  金额：" + askPrice + " 客户端订单id：" + clientOrderId+"  order="+sellLimitId);


        return sellLimitId;
    }

    public static Long createLimitSellOrder(String apikey, String secret, String clientOrderId, String symbol, BigDecimal amount) {
        //新建卖出账单服务
        TradeClient tradeService = TradeClient.create(HuobiOptions.builder()
                .apiKey(apikey)
                .secretKey(secret)
                .build());
        long spotAccountId = account_id(apikey, secret);

        Symbol precision = getPrecision(symbol);
        MarketTicker bizhongPrice = getBizhongPrice(symbol);

        BigDecimal askPrice = bizhongPrice.getClose().setScale(precision.getPricePrecision(), RoundingMode.HALF_UP);
        //.multiply(new BigDecimal(0.998))
        amount = amount.multiply(new BigDecimal(0.998)).setScale(precision.getAmountPrecision(), RoundingMode.HALF_UP);

        if (amount.compareTo(precision.getLimitOrderMinOrderAmt()) <= 0) {
            amount = precision.getLimitOrderMinOrderAmt();
            //return  null;
        }
        if (amount.compareTo(precision.getLimitOrderMaxOrderAmt()) > 0) {
            amount = precision.getLimitOrderMaxOrderAmt();
        }
        amount = amount.setScale(precision.getAmountPrecision(), RoundingMode.HALF_UP);

        System.out.println("火币工具  "+bizhongPrice.getSymbol()+"货币卖出 数量=" + amount + " MAX=" + precision.getLimitOrderMaxOrderAmt() + " MIN=" + precision.getLimitOrderMinOrderAmt());
        CreateOrderRequest sellLimitRequest = CreateOrderRequest
                .spotSellLimit(spotAccountId, symbol, askPrice, amount);
        Long sellLimitId = tradeService.createOrder(sellLimitRequest);

        System.out.println("spotAccountId=:" + spotAccountId + " 出手了：" + symbol + " 数量：" + amount
                + "  金额：" + askPrice + " 客户端订单id：" + clientOrderId+"  order="+sellLimitId);


        return sellLimitId;
    }

    public static Order Order(String apikey, String secret, long orderId) {
        TradeClient tradeService = TradeClient.create(HuobiOptions.builder()
                .apiKey(apikey)
                .secretKey(secret)
                .build());
        Order getOrder = tradeService.getOrder(orderId);


        return getOrder;
    }

    //提币
    public static  Long tibi(String apikey,
                             String secret,
                             String withdrawAddress,
                             String withdrawAddressTag,
                             String currency,
                             BigDecimal amount,
                             BigDecimal fee
    ){
        HuobiWalletService walletService = new HuobiWalletService(HuobiOptions.builder()
                .apiKey(apikey)
                .secretKey(secret)
                .build());

        long withdrawId = walletService.createWithdraw(CreateWithdrawRequest.builder()
                .address(withdrawAddress)
                .addrTag(withdrawAddressTag)
                .currency(currency)
                .amount(amount)
                .fee(fee)
                .build());

        System.out.println("-----------提币ok : "+withdrawId+"------------------");

        return withdrawId;
    }


    //得到账户流水记录
    public static List<AccountLedger> getAccountLiushui(String apikey, String secretkey) {
        AccountClient accountService = AccountClient.create(HuobiOptions.builder()
                .apiKey(apikey)
                .secretKey(secretkey)
                .build());
        long accountId = account_id(apikey, secretkey);

        AccountLedgerResult accountLedgerResult = accountService.getAccountLedger(AccountLedgerRequest.builder()
                .accountId(accountId)
                .limit(2)
                .build());
        System.out.println("leger nextId: " + accountLedgerResult.getNextId());
        accountLedgerResult.getLedgerList().forEach(ledger -> {
            System.out.println(ledger);
        });
        List<AccountLedger> ledgerList = accountLedgerResult.getLedgerList();

        return ledgerList;
    }
    //得到充币提币账单
    public static  List<DepositWithdraw> getWalletLiushui(String apikey, String secret, DepositWithdrawTypeEnum type){


            HuobiWalletService walletService = new HuobiWalletService(HuobiOptions.builder()
                    .apiKey(apikey)
                    .secretKey(secret)
                    .build());
            List<DepositWithdraw> depositWithdrawList = walletService.getDepositWithdraw(DepositWithdrawRequest.builder()
                    .type(type)
                    .build());

            return depositWithdrawList;


    }

    //得到账户货币余额
    public static Balance getAccountyue(String apikey, String secretkey) {
        long accountId = account_id(apikey, secretkey);

        AccountClient accountService = AccountClient.create(HuobiOptions.builder()
                .apiKey(apikey)
                .secretKey(secretkey)
                .build());
        AccountBalance accountBalance = accountService.getAccountBalance(AccountBalanceRequest.builder()
                .accountId(accountId)
                .build());
        //账户所有的币种的账户余额
        List<Balance> balanceList = accountBalance.getList();
        for (Balance balance : balanceList) {
            if (balance.getCurrency().equals("usdt")) {
                System.out.println("账户id：" + accountBalance.getId() +
                        " 账户类型：" + accountBalance.getType() +
                        " 余额(usdt):" + balance.getBalance());

                return balance;
            }

        }

        return null;
    }

    //得到账户货币余额
    public static List<Balance>  getAllAccountyue(String apikey, String secretkey) {
        long accountId = account_id(apikey, secretkey);

        AccountClient accountService = AccountClient.create(HuobiOptions.builder()
                .apiKey(apikey)
                .secretKey(secretkey)
                .build());
        AccountBalance accountBalance = accountService.getAccountBalance(AccountBalanceRequest.builder()
                .accountId(accountId)
                .build());
        //账户所有的币种的账户余额
        return accountBalance.getList();
    }

    //用户的账户id

    public static Long account_id(String apikey, String secretkey) {
        AccountClient accountService = AccountClient.create(HuobiOptions.builder()
                .apiKey(apikey)
                .secretKey(secretkey)
                .build());
        List<Account> accountList = accountService.getAccounts();

        return accountList.get(0).getId();
    }

    //货币最新价格
    public static List<MarketTicker> getBizhongPrice() {
        MarketClient marketClient = MarketClient.create(new HuobiOptions());
        //货币价格
        List<MarketTicker> tickerList = marketClient.getTickers();

        return tickerList;
    }

    //货币最新价格
    public static MarketTicker getBizhongPrice(String bizhongname) {
        MarketClient marketClient = MarketClient.create(new HuobiOptions());
        //货币价格
        List<MarketTicker> tickerList = marketClient.getTickers();

        for (MarketTicker marketTicker : tickerList) {
            if (marketTicker.getSymbol().equals(bizhongname.toString())) {
                return marketTicker;
            }

        }

        return null;
    }


    public static List<AccountLedger> selectadminliushui(String apikey, String secretkey) {

        AccountClient accountService = AccountClient.create(HuobiOptions.builder()
                .apiKey(apikey)
                .secretKey(secretkey)
                .build());
        long accountId = account_id(apikey, secretkey);
        AccountLedgerResult accountLedgerResult = accountService.getAccountLedger(AccountLedgerRequest.builder()
                .accountId(accountId)
                //.limit(1000)
                .build());

        List<AccountLedger> ledgerList = accountLedgerResult.getLedgerList();

        return ledgerList;
    }
}
